using System;
using System.Collections.Generic;
using System.Text;
using EnvDTE80;
using EnvDTE;
using System.Windows.Forms;

namespace VSSDKAssist.Assets.Helpers
{
	/// <summary>
	/// Helper responsible for handling VS output window
	/// </summary>
	public class OutputWindowHelper
	{
		#region Fields
		DTE2 dte;
		string paneName;
		#endregion

		#region Constructors
		/// <summary>
		/// Initializes a new instance of the <see cref="OutputWindowHelper"/> class.
		/// </summary>
		/// <param name="dte">The DTE.</param>
		/// <param name="paneName">Name of the pane.</param>
		public OutputWindowHelper(DTE2 dte, string paneName)
		{
			this.dte = dte;
			this.paneName = paneName;
		}
		#endregion

		#region Properties
		private OutputWindowPane pane;

		/// <summary>
		/// Gets the pane.
		/// </summary>
		/// <value>The pane.</value>
		private OutputWindowPane Pane
		{
			get
			{
				if(pane == null)
				{
					pane = GetPane(OutputWindow, this.paneName);
				}

				return pane;
			}
		}

		private OutputWindow outputWindow;

		/// <summary>
		/// Gets the output window.
		/// </summary>
		/// <value>The output window.</value>
		private OutputWindow OutputWindow
		{
			get
			{
				if(outputWindow == null)
				{
					outputWindow = this.dte.ToolWindows.OutputWindow;
				}

				return outputWindow;
			}
		}
		#endregion

		#region Public Implementation
		/// <summary>
		/// Writes the message.
		/// </summary>
		/// <param name="message">The message.</param>
		public void WriteMessage(string message)
		{
			Application.DoEvents();
			Pane.OutputString(message);
			Pane.OutputString(Environment.NewLine);
			Pane.Activate();
			OutputWindow.Parent.Activate();
		}
		#endregion

		#region Private Implementation
		private static OutputWindowPane GetPane(OutputWindow outputWindow, string panelName)
		{
			Guard.ArgumentNotNullOrEmptyString(panelName, "panelName");

			foreach(OutputWindowPane pane in outputWindow.OutputWindowPanes)
			{
				if(pane.Name.Equals(panelName, StringComparison.InvariantCultureIgnoreCase))
				{
					return pane;
				}
			}

			return outputWindow.OutputWindowPanes.Add(panelName);
		}
		#endregion
	}
}